#include "Win32Console.h"

#include <stdio.h>
#include <io.h>

#include <fcntl.h>

#include <fstream>
#include <iostream>


Win32Console::Win32Console()
{
}


Win32Console::~Win32Console()
{
}


HRESULT Win32Console::Create()
{
	intptr_t osfh;

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	FILE *file;

	::AllocConsole();
	if (!::GetConsoleScreenBufferInfo(::GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
		return E_FAIL;
	csbi.dwSize.Y = 500;
	::SetConsoleScreenBufferSize(::GetStdHandle(STD_OUTPUT_HANDLE), csbi.dwSize);
	
	// redirect stdout
	osfh = _open_osfhandle((intptr_t) ::GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
	file = _fdopen(osfh, "w");
	*stdout = *file;
	setvbuf(stdout, NULL, _IONBF, 0);

	// redirect stderr
	osfh = _open_osfhandle((intptr_t) ::GetStdHandle(STD_ERROR_HANDLE), _O_TEXT);
	file = _fdopen(osfh, "w");
	*stderr = *file;
	setvbuf(stderr, NULL, _IONBF, 0);

	// redirect stdin
	osfh = _open_osfhandle((intptr_t) ::GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
	file = _fdopen(osfh, "r");
	*stdin = *file;
	setvbuf(stdin, NULL, _IONBF, 0);

	// redirect cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
	std::ios::sync_with_stdio();
}


void Win32Console::Release()
{
	FreeConsole();
}
